/**
 * 经测试安卓根据传入的scale处理比较快且效果较好，因此采用scale方式处理，直接放大或缩小相应的倍数
 * iOS需要根据fontNum，转换成对应的scale比例
 */
import {getCustomUAParam} from '@/utils/CommonUtil';



(function flexible (window, document) {
    var docEl = document.documentElement
    var dpr = window.devicePixelRatio || 1
    var ua = navigator.userAgent;

    var scale = 1;
    var scaleStr = "";

    var isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
    var isIPhone = isIOSMobile();
    if(isAndroid) {
        scaleStr = getCustomUAParam('scale', ua);
        if(scaleStr){
            scale = parseFloat(scaleStr);
        }
    } else if(isIPhone) {
        scale = calculateIOSFontScale()
    }

    // adjust body font size
    function setBodyFontSize () {

        if (document.body) {
            document.body.style.fontSize = (12 * dpr) + 'px'
            // alert(document.body.style.fontSize)
        }
        else {
            document.addEventListener('DOMContentLoaded', setBodyFontSize)
        }
    }
    setBodyFontSize();

    // set 1rem = viewWidth / 10
    function setRemUnit () {
        var rem = scale*  docEl.clientWidth / 10
        if(rem >= 70) {
            rem = 70;
        }
        docEl.style.fontSize = rem + 'px'
    }
    setRemUnit()

    function calculateIOSFontScale() {
        var ua = navigator.userAgent;
        var fontNum = getCustomUAParam('fontNum', ua);
        if(fontNum) {
            return 1 + (fontNum-1) / 16;
        }
        return 1;
    }

    function isIOSMobile() {
        var  iPad  =  ua.indexOf('iPad')  >  -1;
        var  iPhone  =  ua.indexOf('iPhone')  >  -1 ;
        if  ( iPad  ||  iPhone)  {
            return  true;
        }
        return  false;
    }

    // reset rem unit on page resize
    window.addEventListener('resize', setRemUnit)
    window.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            setRemUnit()
        }
    })

    // detect 0.5px supports
    if (dpr >= 2) {
        var fakeBody = document.createElement('body')
        var testElement = document.createElement('div')
        testElement.style.border = '.5px solid transparent'
        fakeBody.appendChild(testElement)
        docEl.appendChild(fakeBody)
        if (testElement.offsetHeight === 1) {
            docEl.classList.add('hairlines')
        }
        docEl.removeChild(fakeBody)
    }
}(window, document))